package cn.school.demo

import android.annotation.SuppressLint
import android.app.*
import android.content.Context
import android.content.res.Resources
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.CountDownTimer
import android.view.View
import android.widget.Button
import android.widget.ImageView
import androidx.core.app.NotificationCompat
import androidx.core.net.toUri
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.MutableLiveData
import androidx.navigation.NavController
import cn.school.demo.pojo.*
import cn.school.demo.util.SensitivewordFilter
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.NotificationUtils
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.lzy.imagepicker.ImagePicker
import com.lzy.imagepicker.loader.ImageLoader
import com.lzy.imagepicker.view.CropImageView
import com.mylhyl.circledialog.CircleDialog
import java.io.File
import java.time.LocalDateTime

class MyApplication : Application() {
    companion object {
        const val LIGHT = false
        const val DARK = true

        /*====================================================*/
        var user: User? = null
        val animationCountdown = mutableMapOf<String, Int>()
        val navigateThing = mutableMapOf<String, String>()

        /*================答题所需变量=========================*/
        var testList: MutableList<Test> = mutableListOf(Test(-1, "", "", "", "", "", "", ""))

        @SuppressLint("NewApi")
        var subjectList: MutableList<Subject> = mutableListOf(
            Subject(
                1,
                1,
                "",
                "",
                "",
                "",
                "",
                "",
                "",
                "",
                "",
                "",
                LocalDateTime.now().toString(),
                LocalDateTime.now().toString(),
                1
            )
        )
        val answerScore: AnswerScore = AnswerScore(0, (0.1).toFloat(), "0:00:00", 0, 0)
        var answerTopic: String? = null
        var signId = -1
        var isNoFresh = true
        var isSubject = false

        /*================设置爱好变量===========================*/
        val tabList = mutableListOf<String>("推荐", "要闻", "党史", "法律", "消息")

        /*===============修改用户信息变量===========================*/
        val imagePicker = ImagePicker.getInstance().apply {
            val imagePicker = ImagePicker.getInstance()
            imagePicker.imageLoader = GilderImageLoader() //设置图片加载器
            imagePicker.isShowCamera = true //显示拍照按钮
            imagePicker.isCrop = true //允许裁剪（单选才有效）
            imagePicker.isSaveRectangle = true //是否按矩形区域保存
            imagePicker.isMultiMode = false //多选
            imagePicker.style = CropImageView.Style.CIRCLE //裁剪框的形状
            imagePicker.focusWidth = 800 //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
            imagePicker.focusHeight = 800 //裁剪框的高度。单位像素（圆形自动取宽高最小值）
            imagePicker.outPutX = 1000 //保存文件的宽度。单位像素
            imagePicker.outPutY = 1000
        }
        var bitmap: Bitmap? = null
        var imageUrl: String? = null
        var imageIsModify = false

        /*================== 历史界面所需控制变量 ==================*/
        val historyEditOrSave = MutableLiveData<Boolean>(false)
        val isDelete = MutableLiveData<Boolean>(false)
        var isAll = false

        /*================== 阅读文章界面所需控制变量 ==================*/
        var article: Article? = null
        var isNotify = false
        var articleId = -1
        lateinit var filter: SensitivewordFilter

        /*================== 通知所需控制变量 ==================*/
        var pendingIntent: PendingIntent? = null

        val notifyList = mutableMapOf<String, Notify>()

        /*================== 搜索所需控制变量 ==================*/
        var searchContext: String = ""
        /*====================================================*/

        /*        倒计时动画 */
        fun animationCountdown(view: Button, time: Int?, id: String) {
            time?.let { animationCountdown[id] = time } ?: let { animationCountdown[id] = 60 }
            object : CountDownTimer(time?.let { (time * 1000).toLong() } ?: 60 * 1000, 1000) {
                @SuppressLint("SetTextI18n")
                override fun onTick(millisUntilFinished: Long) {
                    with(view) {
                        isEnabled = false
                        animationCountdown[id] = (millisUntilFinished / 1000).toInt()
                        text = animationCountdown[id].toString() + "秒"

                    }
                }

                override fun onFinish() {
                    LogUtils.d("我执行了！！")
                    with(view) {
                        isEnabled = true
                        text = "重获验证码"
                        animationCountdown.remove(id)
                    }
                }
            }.start()
        }
        /*================================================================*/

        /*        界面跳转 */
        fun goto(id: Int, go: NavController, f: FragmentManager) {
            user?.let {
                go.navigate(id)
            } ?: let {
                CircleDialog.Builder().setText("请先登录！").setNegative("确定", null).show(f)
            }
        }

        fun goto(id: Int, go: NavController, f: FragmentManager, bundle: Bundle) {
            user?.let {
                go.navigate(id, bundle)
            } ?: let {
                CircleDialog.Builder().setText("请先登录！").setNegative("确定", null).show(f)
            }
        }
        /*================================================================*/

        /*        状态栏UI设置 */
        fun systemBarSetting(_is: Boolean, activity: Activity) {
            when (_is) {
                true -> activity.window.apply {
                    //白底黑字
                    statusBarColor = Color.WHITE
                    decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
                }
                else -> activity.window.apply {
                    //红底白字
                    statusBarColor = Color.RED
                    decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                }
            }
        }
        /*================================================================*/

        fun setCircleGlideByUrlString(context: Context, url: String, imageView: ImageView) {
            Glide.with(context) //
                .load(url) //
                .placeholder(R.drawable.no_image_avatar) //
                .error(R.drawable.error_picture_show) //
                .centerCrop()
                .transform(CircleCrop())
                .skipMemoryCache(true)
                .into(imageView)
        }

        /*================================================================*/
    }

    private class GilderImageLoader : ImageLoader {
        override fun displayImage(
            activity: Activity?,
            path: String,
            imageView: ImageView?,
            width: Int,
            height: Int
        ) {
            Glide.with(activity!!) //
                .load(Uri.fromFile(File(path))) //
                .placeholder(R.drawable.button_shape) //
                .error(R.drawable.button_shape) //
                .centerCrop()
                .skipMemoryCache(true)
                .into(imageView!!)
        }

        override fun displayImagePreview(
            activity: Activity?,
            path: String?,
            imageView: ImageView?,
            width: Int,
            height: Int
        ) {

        }

        override fun clearMemoryCache() {
            //这里是清除缓存的方法,根据需要自己实现
        }
    }
}